package com.hsapp.activity;

import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.hsapp.R;
import com.hsapp.adapter.GridAdapter;
import com.hsapp.bean.CSBean;
import com.hsapp.bean.DeptBean;
import com.hsapp.bean.PcsBean;
import com.hsapp.bean.UPResultBean;
import com.hsapp.databinding.ActivityFileBinding;
import com.hsapp.http.MNetHttp;
import com.hsapp.listener.GralleryImgListener;
import com.hsapp.listener.HttpListener;
import com.hsapp.listener.UpImageListener;
import com.hsapp.util.BindingUtil;
import com.hsapp.util.GralleryImgUtil;
import com.hsapp.util.GsonUtil;
import com.hsapp.util.PreferencesUtil;
import com.hsapp.util.Static;
import com.jaredrummler.materialspinner.MaterialSpinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lc on 2017/11/24.
 */
public class FileUpActivity extends BaseActivity {

    private ActivityFileBinding binding;
    private List<String> pathlist;
    private String[] status=new String[]{"正常","异常"};
    private List<CSBean> spannlist;
    private List<PcsBean> pcslist;
    private GridAdapter adapter;
    //private ArrayAdapter spinneradapter,statusadapter;
    private String[] data,pcs;
    private String mainDeptcode="";
    private String zj,pcscode="",zt="0";//0:正常  1：异常
    private android.support.v7.app.AlertDialog.Builder deldialog;

    private int count = 4,selectImg=0;

    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    if (data != null) {
                        //spinneradapter = new ArrayAdapter(FileUpActivity.this, android.R.layout.simple_list_item_1, data);
                       // binding.yycs.setAdapter(spinneradapter);
                        binding.yycs.setItems(data);

                    }else{
                        binding.yycs.setItems("无","无");
                    }
                    binding.yycs.setOnItemSelectedListener(new CSSelectImpl());
                    progressdialog.dismiss();
                    break;
                case 300:
                    if(pcslist!=null){
                        binding.pcsspinner.setItems(pcs);
                        binding.pcsspinner.setOnItemSelectedListener(new PCSelectImpl());
                        binding.pcsspinner.setSelectedIndex(msg.arg1);

                    }

                    break;
                case 200:
                    Static.showToast(FileUpActivity.this, "网络异常");
                    progressdialog.dismiss();
                    break;
            }
        }
    };
    @Override
    protected void after() {
        pathlist = new ArrayList<String>();
        binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_file, null, false);
        binding.setClick(new ViewClick());
        binding.setIsNormal(true);
        AddContentView(binding.getRoot());

        //baseBinding.toolbar.setLogo(ContextCompat.getDrawable(FileUpActivity.this,R.mipmap.znfk));
        //baseBinding.toolbar.setContentInsetsAbsolute(20,0);
        //baseBinding.toolbar.setTitle(R.string.app_name);
        //baseBinding.toolbar.setTitleMargin(10,0,10,0);
        handerBackToolar("图文直播");

        requestGps();
        //postPcs();
        postDept();
        deldialog = new android.support.v7.app.AlertDialog.Builder(FileUpActivity.this);
        deldialog.setCancelable(true);
        deldialog.setTitle("提示");
        deldialog.setMessage("确定要删除这张照片吗？");
        deldialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                pathlist.remove(selectImg);
                adapter.notifyDataSetChanged();
            }
        });
        //statusadapter=new ArrayAdapter(FileUpActivity.this, android.R.layout.simple_list_item_1, status);
        //binding.status.setAdapter(statusadapter);
        binding.status.setItems(status);
        binding.status.setOnItemSelectedListener(new StatusImpl());


    }


    private void postCS(String gxdwdm) {//3
        Map<String,String> params = new HashMap<String,String>();
        params.put("gxdwdm",gxdwdm);
        MNetHttp.getInstance().postRequest(Static.CSLIST, params, new SpinnerCsResult());
    }

    private void postPcs(){//2

        MNetHttp.getInstance().postRequest(Static.PCSLIST,new HashMap<String, String>(),new SpinnerPcsResult());
    }

    private void postDept(){//1
        showProgress("加载数据");
        Map<String,String> params = new HashMap<String,String>();
        params.put("fPolice_No", PreferencesUtil.getInstance(FileUpActivity.this).getLastLoginPoliceCode());
        MNetHttp.getInstance().rxPostRequest(Static.DEPTCODE, params, DeptBean.class, new HttpListener() {
            @Override
            public void success(Object obj) {
                if(((DeptBean)obj).getCode().equals("200")){
                    mainDeptcode=((DeptBean)obj).getData().getDepcode();
                }else{
                    mainDeptcode="";
                }
                postPcs();
            }

            @Override
            public void fail(String msg) {
                progressdialog.dismiss();
                Static.showToast(FileUpActivity.this,msg);
            }
        });
    }


    public class ViewClick {
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.addimgbtn:
                    if(pathlist.size()>3){
                        Static.showToast(FileUpActivity.this,"上传图片不能超过4张");
                    }else {
                        GralleryImgUtil.getInstance(FileUpActivity.this, new GralleryImgImpl()).showImgList();
                    }

                    break;
                case R.id.submit:
                    if(pcscode.equals("")){
                        Static.showToast(FileUpActivity.this,"请先选择派出所");
                    }else{
                        Map<String,String> params=new HashMap<String,String>();
                        params.put("x",Xlocation+"");
                        params.put("y",Ylocation+"");
                        params.put("zt",zt);
                        params.put("ycms", BindingUtil.isTextViewEmpty(binding.ycms));
                        params.put("cjr", PreferencesUtil.getInstance(FileUpActivity.this).getLoginSFZH());//PreferencesUtil.getInstance(FileUpActivity.this).getLoginSFZH());
                        params.put("mjxm",PreferencesUtil.getInstance(FileUpActivity.this).getLastLoginPoliceCode());//PreferencesUtil.getInstance(FileUpActivity.this).getLastLoginPoliceCode());
                        params.put("yycj_zj",zj);
                        params.put("gxdwdm",pcscode);

                        Log.e("Mytext","json--"+GsonUtil.getInstance().getJson(params));
                        MNetHttp.getInstance().rxUpBitmapList(Static.SAVEFILE,pathlist,params,UPResultBean.class,new UpFileResult());

                    }
                    break;
            }
        }
    }

    class CSSelectImpl implements MaterialSpinner.OnItemSelectedListener {


        @Override
        public void onItemSelected(MaterialSpinner materialSpinner, int i, long l, Object o) {
            if(i!=0&&data!=null){
                zj=spannlist.get(i-1).getZj();
            }else{
                zj="";
            }

        }
    }

    class PCSelectImpl implements MaterialSpinner.OnItemSelectedListener{
        @Override
        public void onItemSelected(MaterialSpinner materialSpinner, int i, long l, Object o) {
            if(i==0){
                pcscode="";
            }else{
                pcscode=pcslist.get((i-1)).getDepcode();
                progressdialog.show();
                postCS(pcscode);
            }

        }
    }

    class StatusImpl implements MaterialSpinner.OnItemSelectedListener {


        @Override
        public void onItemSelected(MaterialSpinner materialSpinner, int i, long l, Object o) {
            zt=i+"";
            if(i==0){
                binding.setIsNormal(true);
            }else{
                binding.setIsNormal(false);
            }
        }
    }

    class GralleryImgImpl implements GralleryImgListener {

        @Override
        public void success(String filepath) {
            pathlist.add(filepath);
            if (adapter == null) {
                adapter = new GridAdapter(FileUpActivity.this, pathlist);
                binding.gridView.setAdapter(adapter);//setOnItemClickListener
                binding.gridView.setOnItemClickListener(new GridItemClick());
            } else {
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void fail(String msg) {
            Static.showToast(FileUpActivity.this, msg);
        }
    }

    class SpinnerPcsResult implements HttpListener{

        @Override
        public void success(Object obj) {
            pcslist=GsonUtil.getInstance().jsonToList(obj.toString(), PcsBean[].class);
            //pcscode=pcslist.get(0).getDepcode();
            pcscode="";
            int p=-1;
            pcs=new String[pcslist.size()+1];
            pcs[0]="请选择";
            Message msg=new Message();
            msg.what=300;
            msg.arg1=0;
            for (int i = 0; i < pcslist.size(); i++) {
                pcs[i+1] = pcslist.get(i).getDepshort();
                if(mainDeptcode.equals(pcslist.get(i).getDepcode())){
                    pcscode=pcslist.get(i).getDepcode();
                    msg.arg1=(i+1);
                    p=i;
                }
            }
            handler.sendMessage(msg);

            //handler.sendEmptyMessage(300);
            if(p!=-1){
                postCS(pcslist.get(p).getDepcode());
            }else{
                progressdialog.dismiss();
            }

        }

        @Override
        public void fail(String msg) {
            handler.sendEmptyMessage(200);
        }
    }

    class SpinnerCsResult implements HttpListener {

        @Override
        public void success(Object obj) {
            if(obj.toString().equals("[ ]")){
                spannlist=new ArrayList<CSBean>();
                spannlist.add(new CSBean());
                zj="";
                data=null;//{"无"};
                handler.sendEmptyMessage(100);

            }else{
                spannlist = GsonUtil.getInstance().jsonToList(obj.toString(), CSBean[].class);
                Log.e("Mytext", "--->" + obj.toString());
                zj=spannlist.get(0).getZj();
                data = new String[spannlist.size()+1];
                data[0]="无";
                for (int i = 0; i < spannlist.size(); i++) {
                    data[i+1] = spannlist.get(i).getMc();
                }
                handler.sendEmptyMessage(100);
            }


        }

        @Override
        public void fail(String msg) {
            //progressdialog.dismiss();
            handler.sendEmptyMessage(200);
        }
    }

    class GridItemClick implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectImg=position;
            deldialog.show();
        }
    }

    class UpFileResult implements UpImageListener{

        @Override
        public void start() {
            showProgress("正在上传");
        }

        @Override
        public void success(Object obj) {
            progressdialog.dismiss();
            if(obj.toString().equals("200")){
                Static.showToast(FileUpActivity.this,"提交成功");
                binding.ycms.setText("");
                if(pathlist!=null){
                    pathlist.clear();
                }
                if(adapter!=null){
                    adapter.removeAll();
                }
                finish();
            }else{
                Static.showToast(FileUpActivity.this,Static.UPERROR);
            }


        }

        @Override
        public void failure(String msg) {
            progressdialog.dismiss();
            Static.showToast(FileUpActivity.this,msg);
        }

        @Override
        public void complete() {

        }
    }
}
